﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data.Linq;
using System.Web.Security;
using Orion.Models;
using Orion.MyLib;

namespace Orion.Controllers
{
	[HandleError]
	public class QuestionsController : Controller
	{
		private QuestionRepository m_questionRep = new QuestionRepository( );
		private UserRepository m_userRepository = new UserRepository( );
        private QuestionViewModel m_questView = new QuestionViewModel( );
        UserManager m_userMgr = new UserManager( );
        private int displayQuestions = 100;


		// All Questions
		[Authorize( Roles = "Admin, Staff" )]
		public ActionResult Index( )
		{
            try
            {
                m_questView.Questions = GetQuestionForAllUsers();
                m_questView.counter = m_questView.Questions.Count( );

                //nr of questions per page set.
                m_questView.displayQuestions = displayQuestions;

                //nr of pages calculated
                var q = m_questView.counter;
                m_questView.counter = q / displayQuestions;
                if ( q % displayQuestions != 0 )
                {
                    m_questView.counter++;
                }
                return View( m_questView );
            }
            catch( Exception ex )
            {
                var log = new Logger( );
                log.LogExcepion( ex );
                return View( "Error" );
            }
		}

		//Insert Questions
		[HttpGet]
		public ActionResult Enquiry( int? id )
		{
			//validation
			if( ! id.HasValue )
			{
				return View ("Error" );
			}

			var model = new Question( );
			var recipient = m_userRepository.GetUserById( id.Value );

			//info for recipent added do question
			model.RecipientId = recipient.ID;
			model.Recipient = string.Format( "{0} {1} {2}", recipient.FirstName, recipient.MiddleName, recipient.LastName );
			
			return View( model );
		}

		[HttpGet]
		public ActionResult GetQuestionById( int id )
		{
			var model = m_questionRep.GetQuestionById( id );
			
			return View( model );
		}


		[HttpPost]
		public ActionResult Enquiry( Question question )
		{
			try
			{
				//validation
				if (!ModelState.IsValid)
				{
					return View(question);
				}
				question.QuestionDate = DateTime.Now;
				question.Status = "Nýtt";

				m_questionRep.AddQuestions( question );

				return RedirectToAction("Contact", "Home");
			}
			catch ( Exception ex )
			{
				var log = new Logger( );
				log.LogExcepion( ex );
				return View( "Error" );
			}
			
		}


		[HttpGet]
		[Authorize(Roles = "Admin, Staff" )]
		public ActionResult SendMail( int? id )
		{
			//validation
			if ( ! id.HasValue )
			{
				return View( "Error" );
			}

			var model = m_questionRep.GetQuestionById( id.Value );

			return View( model );
		}
	

		[HttpPost]
		[Authorize(Roles = "Admin, Staff")]
		public ActionResult SendMail( FormCollection form )
		{
			try
			{
				var aq = new Question();

				UpdateModel(aq);

				//validation empty form
				if (form["Answer"].Trim().Length == 0)
				{
					ModelState.AddModelError("Answer", "Spurningu er ósvarað");
					return View( aq );
				}

				//ID is returned as string, for some reason need to change it back to int for use.
				int temp;
				if ( ! int.TryParse( form["ID"], out temp) )
				{
					throw new Exception("ID af auglýsingu tapaðist við tilraun til þess að breyta henni");
				}
				aq.ID = temp;

				if ( aq.Status == "Senda" )
				{
					//answer sent back in email
					EmailMessage em = new EmailMessage();
					em.Subject = aq.Title;
					em.Body = aq.Answer;
					em.From = aq.Recipient;
					em.To = aq.Email;

					EmailService mm = new EmailService();
					mm.SendMessage(em);

					aq.Status = "Sent";
				}
 
				m_questionRep.UpdateQuestion(aq);

				return RedirectToAction("MyQuestions");
			}
			catch (Exception ex)
			{
				var log = new Logger();
				log.LogExcepion(ex);
				return View("Error");
			}
			
		}

		[Authorize]
		public static IEnumerable<Question> GetQuestionForAllUsers()
		{
			QuestionRepository questionRep = new QuestionRepository();
			UserRepository userRep = new UserRepository();

			var question = questionRep.GetQuestions();
			var users = userRep.GetAllUsers();

			//get questions everyone can view
			var model = from q in question
						join u in users
						on q.RecipientId equals u.ID
						where Roles.IsUserInRole(u.aspnet_User.UserName, "General")
						select q;

			return model;
		}

		[Authorize]
		public static IEnumerable<Question> GetQuestionForCurrentUser( )
		{
			QuestionRepository questionRep = new QuestionRepository( );
			UserRepository userRep = new UserRepository( );

			var questions = questionRep.GetQuestions( );
			var users = userRep.GetAllUsers( );

			//question only currently logged on user can view
			var model = from q in questions
						join u in users
						on q.RecipientId equals u.ID
						where u.aspnet_User.UserName == System.Web.HttpContext.Current.User.Identity.Name
						select q;

			return model;
		}

		public ActionResult MyQuestions()
		{
            try
            {
                m_questView.Questions = GetQuestionForCurrentUser();
                m_questView.counter = m_questView.Questions.Count();

                //nr of questions per page set.
                m_questView.displayQuestions = displayQuestions;

                //nr of pages calculated
                var q = m_questView.counter;
                m_questView.counter = q / displayQuestions;
                if (q % displayQuestions != 0)
                {
                    m_questView.counter++;
                }
                return View( m_questView );
            }
            catch (Exception ex)
            {
                var log = new Logger();
                log.LogExcepion(ex);
                return View("Error");
            }
		}
	}
}
